package com.future.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.future.domain.DTO.RoleDTO;
import com.future.domain.Permission;
import com.future.domain.Role;
import com.future.domain.Result;
import com.future.domain.User;
import com.future.mapper.RoleMapper;
import com.future.service.IRoleService;
import com.future.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private AdminService adminService;
    @Override
    public Result listRoles() {
        List<Role> roleList = this.list();
        // 将 Role 列表转换为 RoleDTO 列表
        List<RoleDTO> roleDTOList = roleList.stream()
                .map(role -> {
                    RoleDTO dto = new RoleDTO();
                    BeanUtil.copyProperties(role, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        return Result.ok(roleDTOList);
    }


    @Override
    public Result getRoleById(Long id) {
        Role role = this.getById(id);
        if (role != null) {
            RoleDTO roleDTO = new RoleDTO();
            BeanUtil.copyProperties(role, roleDTO);
            return Result.ok(roleDTO);
        }
        return Result.fail("未找到该角色");
    }

    @Override
    public Result saveRole(RoleDTO roleDTO) {
        // 2. DTO转实体，填充后端字段
        Role role = new Role();
        BeanUtil.copyProperties(roleDTO, role);
        role.setCreatedAt(LocalDateTime.now()); // 后端自动生成创建时间

        try {
            boolean success = this.save(role);
            return success ? Result.ok("新增角色成功") : Result.fail("新增角色失败");
        } catch (Exception e) {
            return Result.fail("新增角色异常：" + e.getMessage());
        }
    }


    @Override
    public Result updateRole(RoleDTO roleDTO) {
        // 1. 校验ID必填
        if (roleDTO.getId() == null) {
            return Result.fail("更新失败：角色ID不能为空");
        }

        // 2. DTO转实体，更新后端字段
        Role role = new Role();
        BeanUtil.copyProperties(roleDTO, role);
        role.setUpdatedAt(LocalDateTime.now()); // 后端自动更新时间

        try {
            boolean success = this.updateById(role);
            return success ? Result.ok("更新角色成功") : Result.fail("更新角色失败");
        } catch (Exception e) {
            return Result.fail("更新角色异常：" + e.getMessage());
        }
    }

    @Override
    public Result deleteRole(Long id) {
        // 1. 校验ID是否为空
        if (id == null) {
            return Result.fail("删除失败：角色ID不能为空");
        }

        try {
            // 2. 校验角色是否存在
            Role existingRole = this.getById(id);
            if (existingRole == null) {
                return Result.fail("删除失败：未找到ID为" + id + "的角色");
            }

            // 3. 执行删除操作
            boolean success = this.removeById(id);
            return success ? Result.ok("删除角色成功") : Result.fail("删除角色失败：数据库操作未成功");
        } catch (Exception e) {
            return Result.fail("删除角色异常：" + e.getMessage());
        }
    }
    @Override
    public List<Permission> selectPermissionsByRoleId(Long roleId) {
        if (roleId == null) {
            throw new IllegalArgumentException("角色ID不能为空");
        }
        // 4. 校验角色是否存在
        Role existingRole = this.getById(roleId);
        if (existingRole == null) {
            throw new IllegalArgumentException("未找到ID为" + roleId + "的角色");
        }
        return getBaseMapper().selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<Role> selectUserRolesByUserId(Long userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        // 5. 校验用户是否存在
        User existingUser = adminService.getById(userId);
        if (existingUser == null) {
            throw new IllegalArgumentException("未找到ID为" + userId + "的用户");
        }
        return getBaseMapper().selectUserRolesByUserId(userId);
    }
}
